package com.qikux.service.impl;

import com.qikux.annotation.Component;
import com.qikux.annotation.Resource;
import com.qikux.annotation.Transactional;
import com.qikux.consts.AppConst;
import com.qikux.dao.DetailDao;
import com.qikux.dao.ResourceDao;
import com.qikux.dao.UserDao;
import com.qikux.dao.impl.UserDaoImpl;
import com.qikux.entity.*;
import com.qikux.service.ResourceService;
import com.qikux.utils.ContextUtils;
import com.qikux.vo.Page;
import com.qikux.vo.ResourceVo;
import com.qikux.vo.ResultVo;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;


@Component
@Transactional
public class ResourceServiceImpl implements ResourceService {

    @Resource
    private ResourceDao resourceDao;
    @Resource
    private DetailDao detailDao;
    @Resource
    private UserDao userDao;
    @Override
    public ResultVo<List<ResourceType>> queryTypes() {

        List<ResourceType> list = new ArrayList<>();

        List<Map<String, Object>> types = resourceDao.findTypes();

        types.stream().reduce(list,(ls,map) ->{
            // 说明此时的类型是一级类型
            if (null == map.get("pid")){
                ResourceType type = ResourceType.builder().id(Long.parseLong(String.valueOf(map.get("id"))))
                        .typeName(String.valueOf(map.get("type_name")))
                        .children(new ArrayList<>())
                        .build();
                list.add(type);

            }else {
                // 如果pid不为空,获取pid的值
                Long pid = Long.parseLong(String.valueOf(map.get("pid")));
                // 根据pid查找List中是否存在父类型
                ResourceType resourceType = list.stream().filter(type -> Objects.equals(pid,type.getId())).findFirst().orElse(null);

                if (resourceType == null){
                    resourceType = ResourceType.builder().id(Long.parseLong(String.valueOf(map.get("pid"))))
                            .typeName(String.valueOf(map.get("ptypename")))
                            .children(new ArrayList<>())
                            .build();
                    list.add(resourceType);
                }
                // resourceType此时一定不为空
                ResourceType type = ResourceType.builder().id(Long.parseLong(String.valueOf(map.get("id"))))
                        .typeName(String.valueOf(map.get("type_name")))
                        .pid(pid)
                        .build();
                resourceType.getChildren().add(type);
            }
            return list;
        },(a,b) -> a);

/*        types.stream().filter(map -> null == map.get("pid") ).forEach(map ->{
            ResourceType type = ResourceType.builder().id(Long.parseLong(String.valueOf(map.get("id"))))
                    .typeName(String.valueOf(map.get("type_name")))
                    .children(new ArrayList<>())
                    .build();
            list.add(type);
        });

        // 过滤二级类型
        types.stream().filter(map -> null != map.get("pid")).forEach(map ->{
            // 先根据二级类型的id,查找一级类型
            Long pid = Long.parseLong(String.valueOf(map.get("pid")));
            ResourceType resourceType = list.stream().filter(type -> Objects.equals(pid,type.getId())).findFirst().orElse(null);

            if (resourceType != null){
                ResourceType type = ResourceType.builder().id(Long.parseLong(String.valueOf(map.get("id"))))
                        .typeName(String.valueOf(map.get("type_name")))
                        .pid(Long.parseLong(String.valueOf(map.get("pid"))))
                        .build();
                resourceType.getChildren().add(type);

            }
        });*/


        return ResultVo.ok().body(list);
    }

    @Override
    public ResultVo<String> saveResource(com.qikux.entity.Resource res) {

        // 将数据直接存储到表中
        resourceDao.saveResource(res);

        // 将上传资源的信息写入到通知表中
        Notice notice = Notice.builder()
                .remark(AppConst.REMARK_UPLOAD)
                .content("您上传的资源" + "《" + res.getResourceName() + "》正在审核中")
                .tagUserId(res.getUserId())
                .resId(res.getId())
                .build();

        detailDao.saveNotice(notice);


        // 给用户添加积分
        // 赠送积分
        Map<String,Object> map = userDao.findScoreConfigByAction(AppConst.REMARK_UPLOAD);
        int score = (int)map.get("score");
        UserScore userScore = UserScore.builder()
                .score(score)
                .remark(AppConst.REMARK_UPLOAD)
                .userId(res.getUserId())
                .resId(res.getId())
                .build();

        userDao.saveUserScore(userScore);

        return ResultVo.ok().message("资源上传成功、1-3个工作日内会完成该资源的审核").build();
    }

    @Override
    public ResultVo<List<ResourceType>> queryReses(String pid) {
        List<Map<String, Object>> reses = resourceDao.findReses(pid);
        return ResultVo.ok().body(reses);
    }

    @Override
    public ResultVo<Page<Map<String, Object>>> queryHot(int i, Page<Map<String, Object>> pageBean) {
        //查询指定
        List<Map<String,Object>> list = resourceDao.findHot(i,pageBean);
        //查询热门资源的总个数
        int count = resourceDao.findResourceHot(i);

        pageBean.setList(list);
        pageBean.setTotalRows(count);
        return ResultVo.ok().body(pageBean);
    }

    /**
     * @description 保存评论
     * @date 2022/9/28 11:50
     * @auther XuHuanDong
     */
    @Override
    public ResultVo<String> saveResComment(ResourceComment resourceComment) {
        //判断用户是否下载过
        List<Map<String, Object>> list = resourceDao.findDownloadResByUserIdAndResId(resourceComment.getUserId(), resourceComment.getResId());
        if (list.isEmpty()){
           return ResultVo.fail("未下载过该资源，暂不能评论").build();
       }
       //判断用户是否评论过该资源
        ResourceComment resComment = resourceDao.findResCommentByUserIdAndResId(resourceComment.getUserId(),resourceComment.getResId());
        if (resComment != null){
            if (resComment.getComStatus() == 1){
                return ResultVo.fail("你已评论过该资源,不可重复评论").build();
            }
            if (resComment.getComStatus() == 0){
                return ResultVo.fail("你的评论正在审核中,不可重复提交").build();
            }
        }
        //保存评论
        resourceDao. saveResComment(resourceComment);
        //根据资源id 查询资源
        ResourceVo resource = detailDao.findResourceById(resourceComment.getResId());
        //根据用户id 查询用户信息
        UserInfo userInfo = userDao.findUserInfoByUserId(resourceComment.getUserId());
        //组装数据
        Notice notice = Notice.builder()
                    .remark(AppConst.COMMENT)
                    .content(userInfo.getNickName() + AppConst.CONTENT_COMMENT + "《"+resource.getResourceName()+"》")
                    .userId(resource.getUserId())
                    .tagUserId(resourceComment.getUserId())
                    .resId(resourceComment.getResId())
                    .build();
            //查询是否已经通知过
            Notice notice1 = detailDao.findNoticeByUserIdAndContent(notice);
            if (notice1 == null){
                detailDao.saveNotice(notice);
            }
        return ResultVo.ok().message("评论已提交、24小时内完成该评论的审核").build();
    }

    @Override
    public ResultVo<Page<Map<String, Object>>> queryRes(int id, Page<Map<String, Object>> pageBean) {
        //查询指定
        List<Map<String,Object>> list = resourceDao.findRes(id,pageBean);
        //查询热门资源的总个数
        int count = resourceDao.findResId(id);

        pageBean.setList(list);
        pageBean.setTotalRows(count);
        return ResultVo.ok().body(pageBean);
    }

    /**
     * 模糊查询
     * @param fname
     * @param pageBean
     * @return
     */
    @Override
    public ResultVo<Page<Map<String, Object>>> queryFuzzy(String fname, Page<Map<String, Object>> pageBean) {
        List<Map<String,Object>> list = resourceDao.findFuzzy(fname,pageBean);
        //查询热门资源的总个数
        int count = resourceDao.findResFuzzy(fname);

        pageBean.setList(list);
        pageBean.setTotalRows(count);
        return ResultVo.ok().body(pageBean);
    }

    @Override
    public ResultVo<List<com.qikux.entity.Resource>> findresources(Long userId) {
        List<Map<String, Object>> qureyresource = resourceDao.qureyresource(userId);
        List<Map<String, Object>> status = qureyresource.stream().filter(p -> p.get("status").equals(1)).toList();
        return ResultVo.ok().body(status);


    }
}
